import os
import allure
from appium import webdriver
from appium.options.common.base import AppiumOptions
from selenium.common import NoSuchElementException
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from ..util.log_util import logger, root_path


class Base:
    def __init__(self, driver=None):
        if driver:
            self.driver = driver
        else:
            options = AppiumOptions()
            options.load_capabilities({
                "platformName": "android",
                "appium:automationName": "uiautomator2",
                "appium:deviceName": "127.0.0.1:7555",
                "appium:appPackage": "com.xueqiu.android",
                "appium:appActivity": ".view.WelcomeActivityAlias",
                "appium:noReset": True,
                "appium:forceAppLaunch": True,
                "appium:ensureWebviewsHavePages": True,
                "appium:nativeWebScreenshot": True,
                "appium:newCommandTimeout": 3600,
                "appium:connectHardwareKeyboard": True
            })
            self.driver = webdriver.Remote("http://127.0.0.1:4723", options=options)
            self.implicitly_wait(10)

    def find(self, by):
        try:
            el = self.driver.find_element(*by)
            return el
        except NoSuchElementException:
            pass

    def finds(self, by):
        try:
            el = self.driver.find_elements(*by)
            return el
        except NoSuchElementException:
            pass

    def find_click(self, by):
        logger.debug(f'定位点击"{by[0]}",元素"{by[1]}"')
        el = self.find(by)
        el.click()

    def find_key(self, by, key):
        logger.debug(f'定位输入"{by[0]}",元素"{by[1]}",输入值"{key}"')
        el = self.find(by)
        el.send_keys(key)

    def find_text(self, by):
        logger.debug(f'定位获取text"{by[0]}",元素"{by[1]}"')
        el = self.find(by)
        return el.text

    def img_log(self, img_name, img_allure):  # 截图,img_name保存在本地的图片名字,img-allure上传到allure的名字
        images_dir1 = os.path.dirname(root_path)
        images_dir2 = os.path.join(images_dir1, "img_log")
        os.makedirs(images_dir2, exist_ok=True)
        screenshot_path = os.path.join(images_dir2, f"{img_name}.png")

        try:
            if self.driver.get_screenshot_as_file(screenshot_path):
                allure.attach.file(screenshot_path, name=img_allure,
                                   attachment_type=allure.attachment_type.PNG)
                logger.debug(f'截取当前页面,保存图片"{screenshot_path}",并上传到 allure 中')
        except Exception as e:
            logger.debug(f'截图操作时发生错误"{e}"')

    def wait(self, method, time_out=5):     # 显式等待,method:*by,time_out等待时间
        logger.debug(f'显式等待定位"{method},时间"{time_out}"')
        el = WebDriverWait(self.driver, time_out).until(expected_conditions.visibility_of_element_located(method))
        return el

    def implicitly_wait(self, time_out=10):     # 隐式等待
        logger.debug(f'修改了隐式等待时间为"{time_out}"')
        self.driver.implicitly_wait(time_out)

    def swip(self, duration=1000):  # 滑动    duration时间(毫秒)
        logger.debug(f'正在滑动,时间为"{duration}"')
        size = self.driver.get_window_size()
        height = size.get('height')
        width = size.get('width')
        start_x = width * 0.5
        start_y = height * 0.8
        end_x = width * 0.5
        end_y = height * 0.2
        self.driver.swipe(start_x, start_y, end_x, end_y, duration)

    def swip_by(self, by, duration=1000, max_count=5):   # 重复滑动查找元素
        logger.debug(f'正在重复滑动查找元素"{by}"')
        count = 0   # 计数
        self.implicitly_wait(1)
        while count < max_count:
            count += 1
            self.swip(duration)
            if self.find(by):
                self.implicitly_wait(10)
                break
